<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Models\News\News;
use Encore\Admin\Form;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Grid;
use App\Models\News\NewsClass;
use App\Models\News\CollectNews;
use App\Models\Artists\Artist;
use App\Models\Artists\NewsArtists;
use App\Models\News\NewsContent;
use App\Models\News\Tag;
use Illuminate\Support\Facades\Auth;
use App\Admin\Extensions\Tools\Build as BuildButton;
use App\Helper\Build\Build;
use Encore\Admin\Widgets\Table;
use App\Helper\OpenSearch\Search;

use App\Helper\CollectNewsContent;
class NewsController extends Controller
{
    protected $name = '新闻管理';
    use ModelForm;
    
    public function index()
    {
		// $this->replace_content();
        return Admin::content(function (Content $content) {

            $content->header($this->name);
            $content->description($this->name);


            $content->body($this->grid());
        });
    }
	//替换内容里图片地址
	public function replace_content()
	{
		$list = NewsContent::where('new_id', '>', 238692)->get();
		
		foreach($list as $row)
		{
			$row->content =  str_replace('http://static.zhuoke.zhiyuanch.com', 'http://static.zhuoke.cn', $row->content);
			$row->save();
		}
	}
    
    /**
     * Edit interface.
     *
     * @param $id
     *
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header($this->name);
            $content->description('编辑');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->name);
            $content->description('创建');
			if(request()->get('c_id', 0) >0)
			{
				$info = CollectNews::find(request()->get('c_id', 0));
				$CollectNewsContent = new CollectNewsContent($info);
				$content->body($this->formCollect($CollectNewsContent->collectNews()));
			}else{
				$content->body($this->form());
			}
            
        });
    }
	
	//关键词搜索
	public function keyword()
	{
		$data = request()->all();
		$list = News::where('title', 'like', '%'.$data['k'].'%')->limit(10)->get();
		if($list->isEmpty())
		{
			return ['status'=>0,'msg'=> '没有了'];
		}
		$headers = ['Id', '标题', '操作'];
		$rows = [];
		foreach($list as $k=>$row)
		{
			$t = '';
			if($row->titlepic)
			{
				$t = '[图]';
			}
			$url = admin_base_path('positionlist/create?position_id='.$data['position_id'].'&new_id='.$row->id);
			$rows[] = [
				$row->id, $row->title.$t, '<a class="btn btn-info btn-sm" href="'.$url.'"><i class="fa fa-mouse-pointer"></i>&nbsp;选择</a>'
			];
		}
		$table = new Table($headers, $rows);
		return ['status'=>1,'content'=> $table->render()];
	}
    //关键词
    public function tags()
    {
        $q = request()->get('q');

        $list = Tag::where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
		
		if(strstr($q, 'C'))
		{
			$q = str_replace('C', '', $q);
			$tag = new Tag();
			$tag->name = str_replace('C', '', $q);
			$tag->save();
			$list = Tag::where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
		}
		return $list;
    }
	
	
	public function build()
	{
		$data = request()->all();
		if(empty($data['id']))return ['status'=>0, 'message'=> '请勾选要生成的稿件.'];
		
		$ids = explodeId($data['id']);
		
		$list = News::whereIn('id', $ids)->get();
		
		$Build = new Build();
		$msg = '';
		foreach($list as $row)
		{
			
			$arr = $Build->news($row);
			$msg .= $arr['msg'].chr(10);
		}
		return ['status'=>1, 'message'=> $msg];
	}
    
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(News::class, function (Grid $grid) {
            $grid->model()->orderBy('id', 'DESC');
            $grid->tools(function ($tools) {
				$tools->append(new BuildButton());
			});
            $grid->filter(function($filter){
            
                // 去掉默认的id过滤器
                //$filter->disableIdFilter();
                
                $filter->useModal();
            
                // 在这里添加字段过滤器
                
                $filter->equal('class_id','栏目')->select(NewsClass::selectOptions());
                $filter->like('title', '标题');
                //$filter->addFilter($filter->like('post_title', '标题'));
                
            
            });
            
			$grid->actions(function ($actions) {
				$id = $actions->getKey();
				$url = news_url($actions->row->created_at, $id, true);//.'?r='.rand(0,1000000000);
				$actions->append('<a href="'.$url.'" target="_blank"><i class="fa fa-eye" title="预览" ></i></a>');
                $actions->disableView();
			});
    
            $grid->column('id', 'ID')->sortable();
            $grid->column('title', '标题');
            
            $grid->column('news_class.name', '栏目');
            $grid->column('source', '来源');
            $grid->column('admin_user.name', '发布');
            $grid->column('admin_edit_user.name', '最后更新');
            
            // $grid->column('status','推荐')->options()->select(News::$status);
            
            $grid->column('created_at', '创建时间');
        });
    
	}
    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(News::class, function (Form $form) {
            
            $form->number('id', 'ID')->attribute('disabled', false);
            $form->text('title', '标题')->rules('required|min:3');
			$form->text('ftitle', '副标题');
			
            $form->multipleSelect('tags', '关键词')->options(function($ids){
                if($ids)
                    return Tag::find($ids)->pluck('name', 'id');
                else
                    return [];
            })->ajax('/admin/news/api/tags')->help('大写字母C，放在最后可以创建该关键词，例如：合肥C, 艺术家C');
            
            // $form->text('index_title', '首页标题');
            // $form->text('keywords', '关键词');
            $form->text('description', '摘要');
            $form->text('source', '来源')->rules('nullable');
            $form->text('titleurl', '链接')->help('选填');
            $form->image('titlepic','标题图片')->uniqueName();
            $form->text('onclick', '点击数')->default(rand(50,100));
            $form->number('listorder', '排序');
            $form->radio('status','审核状态')->options(News::$status)->default('1');
            $form->select('class_id', '栏目')->options(NewsClass::selectOptions())->rules('required|min:0');
            
            $form->editor('content.content', '内容');
			$form->datetime('content.created_at', '创建时间');
            // $form->hidden('edit_user_id');
			
            
			
			$form->saved(function (Form $form) {
                
				$Build = new Build();
				$news_info = News::find($form->model()->id);
				$Build->news($news_info);
				
			});
        });
    }
	protected function formCollect($info)
    {
        return Admin::form(News::class, function (Form $form) use ($info) {
            
            $form->number('id', 'ID')->attribute('disabled', false);
            $form->text('title', '标题')->rules('required|min:3')->default($info['title']);

			// $form->text('head_title', '索引标题');
			
            $form->multipleSelect('tags', '关键词')->options(function($ids){
                if($ids)
                    return Tag::find($ids)->pluck('name', 'id');
                else
                    return [];
            })->ajax('/admin/news/api/tags')->help('大写字母C，放在最后可以创建该关键词，例如：合肥C, 艺术家C');
            
            // $form->text('index_title', '首页标题');
            // $form->text('keywords', '关键词');
            $form->text('description', '摘要');
            $form->text('source', '来源')->rules('nullable')->default($info['source']);
            $form->text('titleurl', '链接')->help('选填');
            $form->image('titlepic','标题图片')->uniqueName();
            $form->text('onclick', '点击数')->default(rand(50,100));
            $form->number('listorder', '排序');
            $form->radio('status','审核状态')->options(News::$status)->default('1');
            $form->select('class_id', '栏目')->options(NewsClass::selectOptions())->rules('required|min:0');
            
            $form->editor('content.content', '内容')->default($info['content']);;
			$form->datetime('content.created_at', '创建时间');
            // $form->hidden('edit_user_id');
			$form->hidden('c_id')->default(request()->get('c_id', 0));
            $form->ignore(['c_id']);

			$form->saved(function (Form $form) {
                
				$Build = new Build();
				$news_info = News::find($form->model()->id);
				$Build->news($news_info);
				//插入到开放搜索
				$Search = new Search();
				// $Search->news_one($news_info);
                $info = (NewsArtists::where('new_id',$form->model()->id)->first());
                if($info)
                {
                    $info->class_id = $form->model()->class_id;
                    $info->save();
                }
			});
        });
    }
}
